<?php
/**
 * BaseController.class.php
 * 基类控制器
 * 
 * @author  王中艺 <wangzy_smile@qq.com>
 * @date    2017-08-30
 */

namespace Common\Controller;
use Think\Controller;

class BaseController extends Controller {

    //变量声明
    protected   $res, $req;

    //构造函数
    function __construct(){
        parent::__construct();

        $this->req  = array_merge(
            (array)I('request.'),
            (array)json_decode(file_get_contents('php://input'), true)
        );
        
    }

     /**
     * 非空参数检测
     * @param   $params     参数列表
     * @return  $client
     */
    function unEmptyParams($params){
        $client     = [];
        foreach($params as $param){
            if($this->request($param) === null){
                $this->response('参数'.$param.'未找到!', -1);
            }
            $client[$param] = $this->request($param);
        }

        return $client;
    }

     /**
     * 获取客户端参数
     * @param   $key
     * @param   $default
     * @return  $value
     */
    function request($key, $default = null){
        return isset($this->req[$key]) && $this->req[$key] !== '' ? 
            $this->req[$key] : $default;
    }

    /**
     * 响应客户端数据
     * @param   $data   数据
     * @param   $code   响应码
     */
    function response($data = 'Oh yes!', $code = 1){
        $this->res['code']    = $code;
        if($data){
            if(is_array($data)){
                $this->res['data']  = (array)$this->res['data'] + $data;
            }else{
                $this->res['data']    = $data;
            }
        }else{
            $this->res['data']    = C('ERROR_CODE.'.$code) ? C('ERROR_CODE.'.$code) : '未定义错误!';
        }
        
        //服务器时间响应
        $this->res['datetime']  = date('Y-m-d H:i:s');

        //记录请求响应数据
        \Think\Log::record(json_encode($this->req), 'INFO');
        \Think\Log::record(json_encode($this->res), 'INFO');
        \Think\Log::save();

        echo json_encode($this->res);
        exit;
    }
}